<?php
class cmsEditAction extends sfActions
{
	public function execute($request)
	{
		$this->cms_id = $request->getParameter('cms_id');
		if ($this->cms_id) {
			$this->cms = Doctrine_Core::getTable('VTNSCms')->find($this->cms_id);
			if ($this->cms)
				$this->cms_form = new AdminCmsForm($this->cms);
		}
        else {
            $this->cms_form = new AdminCmsForm();
        }
		if ($request->hasParameter('cms')) {
			$form = $request->getParameter('cms');
			$this->status = $this->updateCmsFromRequest($this->cms, $form);
			try {
				$files = $this->getRequest()->getFiles();
				$file = $files['cms']['picture'];
                // delete file if it exist
                if($file['size'] > 0) {
                    if(isset($this->cms->picture) && $this->cms->picture != null) {
                        foreach($this->cms->dimensions as $dimension) {
                            $path_file = "uploads/cms/".$dimension['name'].$this->cms->picture;
                            if(file_exists($path_file))
                                unlink($path_file);
                       }
						$path_file = $this->cms->picture;
						if(file_exists($path_file))
						   unlink($path_file);
					}
				    
					$tmpName = $file['tmp_name'];
					$fileName = $file['name'];
					$fileExt = trim(strrchr($fileName, '.'));
					  
					$fileName = ($this->cms->cms_id).$fileExt;
					$img = new sfImage($tmpName, $file['type']);
					$img->saveAs(sfConfig::get('sf_upload_dir').'/cms/'.$fileName, $file['type']);
						
					foreach($this->cms->dimensions as $dimensions) {
						$fileName1 = $dimensions['name'].($this->cms->cms_id).$fileExt;                    
						$img = new sfImage($tmpName, $file['type']);
						if($dimensions['width'] != 0 && $dimensions['height'] != 0 )
							$img->thumbnail($dimensions['width'], $dimensions['height'], 'center');
						$img->setQuality(100);
						$img->saveAs(sfConfig::get('sf_upload_dir').'/cms/'.$fileName1, $file['type']);                            
					}
						
					$this->cms->picture = $fileName;
					$this->upload_success = true;		
				}
			} catch (sfException $e) {
				echo $e->getMessage();
			}
			
			if ($this->status) {
				$this->cms->save();
				$this->redirect('cms/cmsList?cms_category_id='.$this->cms->cms_category_id);
			} else
				return SfView::SUCCESS;
		} else
			return SfView::SUCCESS;
		
	}
	
	
	private function updateCmsFromRequest(&$cms, $form)
	{
		if ($form['content'])
			$cms->content = $form['content'];
		if ($form['name'])
			$cms->name = $form['name'];	
		if (isset($form['is_active']))
			$cms->is_active = 1;
		else
			$cms->is_active = 0;
		if ($form['description'])
			$cms->description = $form['description'];

		$cms->updated_at = date(DATE_ISO8601);
		return true;
	}
}
?>